<template>
    <div>
        <template>
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                <!-- 基本信息 start -->
                <el-tab-pane label="基本信息" name="first">
                    <el-descriptions title="基本信息">
                        <el-descriptions-item label="合同标题">{{ info.title }}</el-descriptions-item>
                        <el-descriptions-item label="客户名称">{{ info.client }}</el-descriptions-item>
                        <el-descriptions-item label="类型">{{ info.type1 }}-{{ info.type2 }}</el-descriptions-item>
                        <el-descriptions-item label="状态">{{ info.state }}</el-descriptions-item>
                        <el-descriptions-item label="状态">
                            <el-tag size="small">进行中</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="联系地址">江苏省苏州市吴中区吴中大道 1188 号</el-descriptions-item>
                    </el-descriptions>
                </el-tab-pane>
                <!-- 基本信息 end -->

                <!-- 历年合同 start -->
                <el-tab-pane label="历年合同" name="first2">

                    <el-button type="success" round @click="openEditUI(null)">新增年份合同</el-button>

                    <template>
                        <el-table :data="info.infoList" stripe style="width: 100%">
                            <el-table-column prop="year" label="年份">
                            </el-table-column>
                            <el-table-column prop="money" label="合同金额">
                            </el-table-column>
                            <el-table-column prop="start_at" label="开始时间" width="180">
                            </el-table-column>
                            <el-table-column prop="end_at" label="结束时间" width="180">
                            </el-table-column>
                            <el-table-column prop="linkman" label="联系人">
                            </el-table-column>
                            <el-table-column label="操作" prop="desc">
                                <template slot-scope="scope">
                                    <el-button type="primary" round @click="openEditUI(scope.row.id)">修改</el-button>
                                    <el-button type="danger" round @click="handleDelete(scope.row.id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-tab-pane>
                <!-- 历年合同 end -->

                <!-- 收费/缴费 start -->
                <el-tab-pane label="收费/缴费" name="second">
                    <template>
                        <el-table :data="info.tableData" stripe style="width: 100%">
                            <el-table-column prop="eachmoney" label="应收金额">
                            </el-table-column>
                            <el-table-column prop="ought_to_money_time" label="应收时间" width="180">
                            </el-table-column>
                            <el-table-column prop="practical_money" label="实收金额">
                            </el-table-column>
                            <el-table-column prop="practical_money_time" label="实收时间">
                            </el-table-column>
                            <el-table-column prop="invoice_money" label="发票金额">
                            </el-table-column>
                            <!-- <el-table-column prop="eachmoney" label="备注">
                            </el-table-column> -->
                            <el-table-column label="操作" prop="desc">
                                <template slot-scope="scope">
                                    <el-button type="success" round
                                        @click="openPayEditUI(scope.row.id)">确认收款/修改</el-button>

                                    <!-- <router-link :to="{ path: '/contract/updateContract', query: { id: scope.row.id } }">
                                        <el-button type="primary" round>确认收款</el-button>
                                    </router-link> -->
                                    <!-- <router-link :to="{ path: '/contract/detailContract', query: { id: scope.row.id } }">
                                        <el-button type="primary" round>详情</el-button>
                                    </router-link>
                                    <el-button type="danger" round>删除</el-button> -->

                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-tab-pane>
                <!-- 收费/缴费 end -->

                <!-- 合同文件 start -->
                <el-tab-pane label="合同文件" name="fourth">
                    <el-tooltip class="item" effect="dark" :content="tag.name" placement="top-start"
                        v-for="(tag, index) in fileList" :key="index">
                        <el-tag style="margin-right:10px;display:flex;" :disable-transitions="false"
                            @close="handleClose(index)" closable @click="downloadFile(tag)"><i
                                class="el-icon-paperclip"></i><span class="tagtext">{{ tag.name
                                }}</span></el-tag>
                    </el-tooltip>
                    <el-upload class="upload-demo" drag action="" :headers="headers" :limit="fileLimit"
                        :file-list="fileList" :on-exceed="handleExceed" :before-upload="beforeUpload"
                        :http-request="upload" multiple>
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                    <div class="block">
                        <el-timeline>

                            <el-timeline-item v-for="(infoFile, index) in infoFileList" timestamp="2018/4/12"
                                placement="top">
                                <el-card>
                                    <h4>{{ infoFile.title }}</h4>
                                    <p>提交于 {{ infoFile.created_at }}</p>
                                </el-card>
                            </el-timeline-item>


                        </el-timeline>
                    </div>
                </el-tab-pane>


                <!-- 合同文件 end -->

                <el-tab-pane label="绩效提成" name="fourth1">
                    <template>
                        <el-collapse v-model="activeNames" @change="handleChange">
                            <div v-for="(modulesitem, index) in jixiaoList" :key="index">
                                <el-collapse-item :title="modulesitem.info_title" :name="index">
                                    <el-table :data="modulesitem.project" style="width: 100%">
                                        <el-table-column type="expand">
                                            <template slot-scope="props">
                                                <el-form label-position="left" inline class="demo-table-expand">
                                                    <template>
                                                        <el-table :data="props.row.member" stripe style="width: 80%">
                                                            <el-table-column prop="userInfo.username" label="姓名"
                                                                width="180">
                                                            </el-table-column>
                                                            <el-table-column prop="userInfo.gs" label="提成系数"
                                                                width="180">
                                                            </el-table-column>
                                                            <el-table-column prop="allManhour" label="工时">
                                                            </el-table-column>
                                                            <el-table-column prop="allMoney" label="绩效金额">
                                                            </el-table-column>
                                                        </el-table>


                                                    </template>
                                                </el-form>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="项目编号" prop="number">
                                        </el-table-column>
                                        <el-table-column label="项目名称" prop="title">
                                        </el-table-column>
                                        <el-table-column label="地址" prop="address">
                                        </el-table-column>
                                    </el-table>
                                </el-collapse-item>
                            </div>
                        </el-collapse>

                    </template>
                </el-tab-pane>
            </el-tabs>
        </template>

        <!-- 添加年份合同 -->
        <el-dialog @close="clearForm" :title="formTitle" id="addUser" :visible.sync="dialogFormVisible">
            <el-form :model="form" ref="formRef">
                <el-form-item label="选择年份">
                    <el-select v-model="form.year" placeholder="选择年份">
                        <el-option label="2023" value="2023"></el-option>
                        <el-option label="2024" value="2024"></el-option>
                        <el-option label="2025" value="2025"></el-option>
                        <el-option label="2026" value="2026"></el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="时间范围">
                    <el-date-picker :value-format="'yyyy-MM-dd HH:mm:ss'" v-model="form.time" type="daterange"
                        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>


                <el-form-item label="合同金额">
                    <el-col :span="12">
                        <el-input v-model="form.money" placeholder="输入合同金额" />
                    </el-col>
                </el-form-item>


                <el-form-item label="联系人">
                    <el-col :span="12">

                        <el-input v-model="form.linkman" placeholder="输入联系人" />
                    </el-col>

                </el-form-item>

                <el-form-item label="联系电话">
                    <el-col :span="12">
                        <el-input v-model="form.phone" placeholder="输入联系电话" />
                    </el-col>
                </el-form-item>

                <el-form-item label="文档链接">
                    <el-col :span="20">
                        <el-input v-model="form.document_link" placeholder="输入文档链接" />
                    </el-col>
                </el-form-item>

                <div>
                    <div class="collapse2-titlebox">
                        <span class="collapse2-titlebox-t">提示:填写每个收费节点日期与金额</span>
                        <div class="collapse2-title-right">
                            <span class="jia" @click="clickAdd">+</span>
                            <span class="jian" @click="clickMinus">-</span>
                        </div>
                    </div>
                    <br>
                    <div class="collapse2-listbox">
                        <el-form-item label="选择收费节点">
                            <el-select v-model="form.jie" placeholder="选择收费节点">
                                <el-option label="年付" value="年付"></el-option>
                                <el-option label="半年付" value="半年付"></el-option>
                                <el-option label="季付" value="季付"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-table ref="multipleTable" :data="form.tableData" tooltip-effect="dark" style="width: 100%">
                            <el-table-column type="selection"></el-table-column>
                            <el-table-column prop="eachmoney" label="金额" width="120">
                                <template slot-scope="scope">
                                    <el-input type="text" v-model="scope.row.eachmoney"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="ought_to_money_time" label="时间" width="500">
                                <template slot-scope="scope">
                                    <el-date-picker :value-format="'yyyy-MM-dd HH:mm:ss'"
                                        v-model="scope.row.ought_to_money_time" type="date" placeholder="选择日期">
                                    </el-date-picker>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="clickConfirm">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 添加年份合同 -->

        <!-- 确认收款 -->
        <el-dialog @close="clearForm" :title="formTitle" id="addUser" :visible.sync="dialogFormVisible1">
            <el-form :model="payForm" ref="formRef">
                <el-form-item label="实收金额">
                    <el-col :span="12">
                        <el-input v-model="payForm.practical_money" placeholder="输入实收金额" />
                    </el-col>
                </el-form-item>


                <el-form-item label="实际收款时间">
                    <el-col :span="12">
                        <el-date-picker v-model="payForm.practical_money_time" type="date"
                            :value-format="'yyyy-MM-dd HH:mm:ss'" placeholder="选择实际收款时间">
                        </el-date-picker>
                    </el-col>
                </el-form-item>

                <el-form-item label="选择发票类型">
                    <el-select v-model="payForm.invoice_type" placeholder="请选择发票类型">
                        <el-option label="请选择" value=""></el-option>
                        <el-option label="专用发票" value="专用发票"></el-option>
                        <el-option label="普通发票" value="普通发票"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="发票税率">
                    <el-col :span="12">
                        <el-input v-model="payForm.invoice_tax_rate" placeholder="输入发票税率" />
                    </el-col>
                </el-form-item>

                <el-form-item label="发票金额">
                    <el-col :span="20">
                        <el-input v-model="payForm.invoice_money" placeholder="输入发票金额" />
                    </el-col>
                </el-form-item>



            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible1 = false">取 消</el-button>
                <el-button type="primary" @click="clickConfirmPay">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 确认收款 -->
    </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import contractApi from '@/api/contract'

export default {

    data() {
        return {

            headers: {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'multipart/form-data',
                "Authorization": ''
            },
            dialogTableVisible: false,
            dialogFormVisible: false,

            dialogFormVisible1: false,


            activeName: 'first',
            id: '',
            info: {},
            infoFileList: [],

            formTitle: '',
            form: {
                tableData: [],
            },

            //收款信息表单
            payForm: {},

            //项目绩效列表
            jixiaoList: [],


            // 文件上传
            //上传后的文件列表
            fileList: [],
            // 允许的文件类型
            fileType: ["pdf", "doc", "docx", "xls", "xlsx", "txt", "png", "jpg", "bmp", "jpeg"],
            // 运行上传文件大小，单位 M
            fileSize: 50,
            // 附件数量限制
            fileLimit: 5,

            //折叠面板  
            activeNames: ['1'],
        };
    },
    methods: {
        //打开添加/修改年份合同
        openEditUI(id) {
            if (id == null) {
                this.formTitle = "新增年份合同";
            } else {
                this.formTitle = "修改年份合同";
                //根据id获取证件信息
                contractApi.getContractById(id).then(response => {
                    this.form = response.data.info;
                })
            }
            this.dialogFormVisible = true;
        },

        //打开添加/修改收款记录
        openPayEditUI(id) {
            if (id == null) {
                this.formTitle = "确认收款";
            } else {
                this.formTitle = "修改收款信息";
                //根据id获取收款记录信息
                contractApi.getContractPayInfo(id).then(response => {
                    this.payForm = response.data.info;
                })
            }
            this.payForm.id = id;
            this.dialogFormVisible1 = true;
        },

        //添加/修改年份合同
        clickConfirm() {
            console.log(this.form);
            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    this.form.contract_id = this.id
                    contractApi.saveContractYear(this.form).then(response => {
                        this.$message({
                            message: response.message,
                            type: 'success'
                        });

                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        //添加/修改收款记录
        clickConfirmPay() {
            console.log(this.payForm);
            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    contractApi.saveContractPay(this.payForm).then(response => {
                        this.$message({
                            message: response.message,
                            type: 'success'
                        });
                        this.dialogFormVisible1 = false;
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        //删除年份合同
        handleDelete(id) {

            this.$alert('确认删除此年度合同吗？', '删除合同', {
                confirmButtonText: '确定',
                callback: action => {
                    contractApi.delContractById(id).then(response => {
                        this.$message({
                            message: response.message,
                            type: 'success'
                        });
                        //等待跳转
                        // this.getCredentials()
                    })
                }
            });
        },

        //获取绩效
        getContractJixiao(id) {
            contractApi.getContractJixiao(id).then(response => {
                this.jixiaoList = response.data.list;

            })
        },

        //获取文件列表
        getContractFileList() {

            contractApi.getContractFileList(this.id).then(response => {
                this.infoFileList = response.data.list;
            })

            console.log(123, this.infoFileList);
        },



        //清除form表单
        clearForm() {
            this.form = {};
            this.$refs.formRef.clearValidate();
        },

        handleClick(tab, event) {
            console.log(tab, event);
        },


        //上传文件
        upload(file) {

            const formData = new FormData()
            formData.append('excel', file.file)


            this.$axios({
                method: 'post',
                url: '/contract_file/add/' + this.id,
                headers: { 'Authorization': 'Bearer ' + getToken() },
                timeout: 30000,
                data: formData
            }).then(res => {
                this.handleSuccess();
            })


        },
        uploadFile() {
            contractApi.uploadFile(formData).then(response => {
                console.log(response.data);
            })
        },
        //上传文件之前
        beforeUpload(file) {

            if (file.type != "" || file.type != null || file.type != undefined) {
                // alert('校验')
                //截取文件的后缀，判断文件类型
                const FileExt = file.name.replace(/.+\./, "").toLowerCase();
                //计算文件的大小
                const isLt5M = file.size / 1024 / 1024 < 50; //这里做文件大小限制
                //如果大于50M
                if (!isLt5M) {
                    this.$showMessage('上传文件大小不能超过 50MB!');
                    return false;
                }
                //如果文件类型不在允许上传的范围内
                if (this.fileType.includes(FileExt)) {
                    return true;
                }
                else {
                    this.$message.error("上传文件格式不正确!");
                    return false;
                }
            }
        },

        //这是我自定义的移除事件
        handleClose(i) {
            this.fileList.splice(i, 1);//删除上传的文件
            if (this.fileList.length == 0) {//如果删完了
                this.fileflag = true;//显示url必填的标识
                this.$set(this.rules.url, 0, { required: true, validator: this.validatorUrl, trigger: 'blur' })//然后动态的添加本地方法的校验规则
            }
        },
        //超出文件个数的回调
        handleExceed() {
            this.$message({
                type: 'warning',
                message: '超出最大上传文件数量的限制！'
            }); return
        },
        //上传文件的事件
        uploadFile(item) {
            this.$showMessage('文件上传中........')
            //上传文件的需要formdata类型;所以要转
            let FormDatas = new FormData()
            FormDatas.append('file', item.file);
            this.$axios({
                method: 'post',
                url: '/file/fileUpload',
                // headers: this.headers,
                timeout: 30000,
                data: FormDatas
            }).then(res => {
                if (res.data.id != '' || res.data.id != null) {
                    this.fileList.push(item.file);//成功过后手动将文件添加到展示列表里
                    let i = this.fileList.indexOf(item.file)
                    this.fileList[i].id = res.data.id;//id也添加进去，最后整个大表单提交的时候需要的
                    if (this.fileList.length > 0) {//如果上传了附件就把校验规则给干掉
                        this.fileflag = false;
                        this.$set(this.rules.url, 0, '')
                    }
                    //this.handleSuccess();
                }
            })
        },
        //上传成功后的回调
        handleSuccess() {

        },


        // 点击增加
        clickAdd() {
            const tableData = this.form.tableData;
            tableData.push({
                name: '',
                appellation: '',
            })
            this.form.tableData = tableData;
        },
        // 点击减号
        clickMinus() {
            const tableData = this.form.tableData;
            if (tableData.length == 1) {
                return
            } else {
                tableData.pop()
            }
            this.form.tableData = tableData;
        },

        //折叠面板
        handleChange(val) {
            console.log(val);
        },



    },
    created() {
        var query = this.$route.query;
        if (query.id) {
            this.id = query.id;
            contractApi.getInfo(query.id).then(response => {
                this.info = response.data.info;
            })
        }

        //获取token
        const TokenKey = 'OA_token'
        this.headers.Authorization = 'Bearer ' + Cookies.get(TokenKey)
        // console.log(this.headers);

        this.getContractJixiao(this.id);
        this.getContractFileList(this.id);
    }
}
</script>

<style>
.collapse2-titlebox {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.collapse2-titlebox-t {
    font-size: 12px;
    color: #666;
}

.collapse2-title-right {
    display: flex;
    align-items: center;
}

.collapse2-title-right>span {
    font-size: 15px;
    font-weight: bold;
    margin-right: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 16px;
    height: 16px;
    color: #fff;
    line-height: 1 !important;
    cursor: pointer;
}

.collapse2-title-right>span.jia {
    background: #409eff;
}

.collapse2-title-right>span.jian {
    background: #999;
}
</style>